<template>
  <el-form :model="login" :rules="rules" ref="login">
    <el-form-item prop="email" required>
      <el-input type="email" v-model="login.email" placeholder="邮箱"></el-input>
    </el-form-item>
    <el-form-item prop="pass" required>
      <el-input type="password" v-model="login.pass" placeholder="密码" auto-complete="off">
        <span slot="append" v-if="strength">{{ strength }}</span>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-row type="flex" justify="space-around">
        <el-button plain @click="submitForm('login')">登录</el-button>
        <el-button plain @click="enroll">注册</el-button>
      </el-row>
    </el-form-item>
  </el-form>
</template>

<script>
import { AuthPostLogin } from '@/utils/request'
import { generate } from '@/utils/crypto'
import { setAuth } from '@/utils/checkAuth'
// TODO: 其他形式登录完善

export default {
  name: 'cl-login-bound',
  data () {
    return {
      login: {
        email: '',
        pass: ''
      },
      strength: '',
      rules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          AuthPostLogin({
            email: this.login.email,
            pass: generate(this.login.pass)
          }).then(rsp => {
            const { success, enroll, profile } = rsp.data
            if (enroll) {
              if (success) {
                const { userId, username, admin } = profile
                setAuth(userId, username, admin)
                this.$router.push({
                  name: 'MarketList'
                })
              } else {
                this.$alert('登录失败')
              }
            } else {
              this.$alert('此邮箱尚未注册')
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    enroll () {
      this.$router.push({
        name: 'EnrollRegister'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
